package com.yugao.fintech.antelope.mps.core.sender;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.yugao.fintech.antelope.mps.api.constatnts.ChannelTypeEnum;
import com.yugao.fintech.antelope.mps.api.constatnts.MsgPushStatus;
import com.yugao.fintech.antelope.mps.api.model.content.MsgContent;
import com.yugao.fintech.antelope.mps.core.PushTaskContext;
import com.yugao.fintech.antelope.mps.core.channel.ChannelClientManager;
import com.yugao.fintech.antelope.mps.core.channel.client.AbstractEmailMsgClient;
import com.yugao.fintech.antelope.mps.core.parser.EmailTemplateParser;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Slf4j
@Service
public class EmailSender implements MsgSender {
    @Autowired
    private ChannelClientManager channelClientManager;

    @Override
    public void sendMessage(PushTaskContext context) {
        AbstractEmailMsgClient msgChannelClient = (AbstractEmailMsgClient) channelClientManager.getChannelClient(context.getChannelType());
        MailProperties mailProperties = msgChannelClient.getMailProperties();
        JavaMailSenderImpl mailSender = msgChannelClient.getJavaMailSender();
        context.setChannelCode(msgChannelClient.channelCode());

        MsgContent msgContent = (MsgContent) context.getMsgContent();

        String fromAddress = mailProperties.getUsername();
        EmailTemplateParser templateConfig = (EmailTemplateParser) context.getTplConfig();
        log.debug("send msg to email, msg: {}", JSON.toJSONString(templateConfig, JSONWriter.Feature.WriteEnumsUsingName));


        MimeMessage message = mailSender.createMimeMessage();
        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(fromAddress);
            helper.setTo(msgContent.getToUser());
            helper.setSubject(StringUtils.isEmpty(msgContent.getTitle()) ? context.getPushTask().getName() : msgContent.getTitle());
            helper.setText(templateConfig.getRenderContent(), true);
            mailSender.send(message);
        } catch (MessagingException | MailAuthenticationException e) {
            context.setPushStatus(MsgPushStatus.FAIL);
            context.setPushResult(e.getMessage());
            log.error("send mail to [{}] fail, error: {}", msgContent.getToUser(), e.getMessage());
            if (e instanceof MailAuthenticationException) {
                throw new BizException("邮箱授权失败-请确认账号以及授权码是否正确");
            }
        }
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.EMAIL;
    }
}
